﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Expressions;
using CanDoo;
using CanDoo.Core;
using CanDoo.Core.Data;
using CanDoo.Data;
using CanDoo.Extensions;
using CanDoo.Oil.Core.Contracts;
using CanDoo.Admin.Core.Contracts;
using CanDoo.Oil.Core.DTOs;
using CanDoo.Oil.Core.Models;

namespace CanDoo.Oil.Core.Services
{
    /// <summary>
    /// 业务实现——客户
    /// </summary>
    public class CustomerService : CanDoo.Data.Entity.Services.ServiceBase<Customer>, ICustomerContract
    {
        public IMoneyChangeContract MoneyChangeContract { get; set; }

        public CustomerService()
        {

        }

        //TODO : 这里要不要改为 OnDelete事件
        public IOilSalesSerialNumContract OilSalesSerialNumContract { get; set; }
        public IOilSerialNumContract OilSerialNumContract { get; set; }
        public IUserContract UserContract { get; set; }
        public override OperationResult DeleteEntity(Customer Entity)
        {
            OperationResult result;
            using (var scope = DbScopeFactory.Create())
            {
                Delete(Entity);
                UserContract.Delete(Entity.Id);
                result = scope.SaveChanges() > 0
                ? new OperationResult(OperationResultType.Success, "数据删除成功!")
                : new OperationResult(OperationResultType.NoChanged);
            }
            //if (result.Succeeded && OnChanged != null)
            //    OnChanged();
            return result;
        }

        public override OperationResult DeleteEntity(IEnumerable<Customer> Entities)
        {
            OperationResult result;
            using (var scope = DbScopeFactory.Create())
            {
                Delete(Entities);
                foreach (var m in Entities)
                    UserContract.Delete(m.Id);
                result = scope.SaveChanges() > 0
                ? new OperationResult(OperationResultType.Success, "数据删除成功!")
                : new OperationResult(OperationResultType.NoChanged);
            }
            //if (result.Succeeded && OnChanged != null)
            //    OnChanged();
            return result;
        }

        public override OperationResult DeleteEntity(Expression<Func<Customer, bool>> predicate)
        {
            var mList = Entities.Where(predicate).ToList();
            return DeleteEntity(mList);
        }

        public override OperationResult DeleteEntity(long id)
        {
            OperationResult result;
            using (var scope = DbScopeFactory.Create())
            {
                Delete(id);
                UserContract.Delete(id);
                result = scope.SaveChanges() > 0
                ? new OperationResult(OperationResultType.Success, "数据删除成功!")
                : new OperationResult(OperationResultType.NoChanged);
            }
            //if (result.Succeeded && OnChanged != null)
            //    OnChanged();
            return result;
        }

        /// <summary>
        /// 根据uid与金额判断会员能否取油
        /// </summary>
        /// <param name="oilTankUserInfo"></param>
        /// <returns>可以取油返回 操作成功,不可取油返回操作失败,并返回不能取油原因</returns>
        public OperationResult CanTakeOil(OilTankUserInfo oilTankUserInfo)
        {
            using (var scope = DbScopeFactory.Create())
            {
                OperationResult result = OperationResult.NoChanged;

                var oilSalesSerialNum = OilSalesSerialNumContract.FirstOrDefault(p => p.TerminalNum == oilTankUserInfo.terminalNo);
                if (oilSalesSerialNum == null)
                {
                    result.ResultType = OperationResultType.ValidError;
                    result.Message = "终端号[" + oilTankUserInfo.terminalNo + "]未找到";
                    return result;
                }


                var entity = SingleOrDefault(p => p.CardNo == oilTankUserInfo.cardNo);
                if (entity == null)
                {
                    result.ResultType = OperationResultType.ValidError;
                    result.Message = "未找到客户";
                    return result;
                }

                var oilSerialNum = OilSerialNumContract.FirstOrDefault(p => p.OilSalesSerialNum.TerminalNum == oilTankUserInfo.terminalNo && p.OilPort == oilTankUserInfo.oilPort && p.Status == OilSerialStatus.OnSale);
                if (oilSerialNum == null)
                {
                    result.ResultType = OperationResultType.ValidError;
                    result.Message = "此出油口未配置油品";
                    return result;
                }
                else
                {
                    if (oilSerialNum.Product.SN != oilTankUserInfo.oilId)
                    {
                        result.ResultType = OperationResultType.ValidError;
                        result.Message = "出油口的油品不符";
                        return result;
                    }
                    else
                    {
                        if (entity.CardType != 2)//如果不是储油卡  那就校验单价  否则不用
                        {
                            var price = (int)(oilSerialNum.Product.RetailPrice * 100);//RetailPrice*100  //转为int
                            if (oilTankUserInfo.price != price)
                            {
                                result.ResultType = OperationResultType.ValidError;
                                result.Message = "油品单价不符";
                                return result;
                            }
                        }
                    }
                }
                
                if (entity.IsOnline)
                {
                    //TODO: 账号锁定功能 暂时解除 记得打开
                    //if (entity.StateUpdateTime != null && entity.StateUpdateTime.ToDateTime().AddMinutes(10) < DateTime.Now)
                    //{
                    //    entity.IsLocked = true;
                    //    Update(entity);
                    //    scope.SaveChanges();

                    //    result.ResultType = OperationResultType.ValidError;
                    //    result.Message = "账户被锁定";
                    //    return result;
                    //}
                }

                if (entity.CardType == 2) //储油卡
                {
                    if (entity.Balance < oilTankUserInfo.millilitre)
                    {
                        result.ResultType = OperationResultType.ValidError;
                        result.Message = "储油量不足";
                        return result;
                    }
                    if (entity.LimitProduct != null)
                    {
                        if (entity.LimitProduct.SN != oilTankUserInfo.oilId)
                        {
                            result.ResultType = OperationResultType.ValidError;
                            result.Message = "本储油卡只允许购买油品[" + entity.LimitProduct.Name + "]";
                            return result;
                        }
                    }
                    else
                    {
                        result.ResultType = OperationResultType.ValidError;
                        result.Message = "本储油卡未配置油品";
                        return result;
                    }
                }
                else
                {
                    if (entity.Balance < (oilTankUserInfo.amount * 0.01))
                    {
                        result.ResultType = OperationResultType.ValidError;
                        result.Message = "余额不足";
                        return result;
                    }
                }
                if (entity.IsLocked)
                {
                    result.ResultType = OperationResultType.ValidError;
                    result.Message = "账户被锁定";
                    return result;
                }
                if (!entity.Status)
                {
                    result.ResultType = OperationResultType.ValidError;
                    result.Message = "账户未激活";
                    return result;
                }
                entity.StoreNo = oilTankUserInfo.terminalNo;
                entity.StateUpdateTime = DateTime.Now;
                Update(entity);

                result = scope.SaveChanges() > 0 ? OperationResult.Success : OperationResult.NoChanged;
                return result;
            }
        }

        /// <summary>
        /// 1.1.6门店介绍 : 
        /// </summary>
        /// <param name="storeNo">门店号</param>
        /// <returns>门店基本信息介绍</returns>
        public StoreIntroduction GetStoreIntroductionByStoreNo(string storeNo)
        {
            using (DbScopeFactory.CreateReadOnly())
            {
                var entity = SingleOrDefault(p => p.CardNo == storeNo);
                if (entity == null)
                    return null;
                return new StoreIntroduction { introduction = entity.Introduction, storeTitle = entity.CardNo, imageUrl = entity.ImageUrl };
            }
        }

        /// <summary>
        /// 1.1.7用户登录
        /// </summary>
        /// <param name="loginInfo">登录信息</param>
        /// <returns>用户信息</returns>
        public UserInfo GetUserInfoByLoginInfo(LoginInfo loginInfo)
        {
            throw new NotSupportedException("请使用oauth2.0认证");
            using (DbScopeFactory.CreateReadOnly())
            {
                var entity = SingleOrDefault(p => p.CardNo == loginInfo.loginName);
                if (entity == null)
                    return null;

                var userInfo = new UserInfo();
                userInfo.id = entity.CardNo.ToString();
                userInfo.city = entity.City;
                userInfo.sex = entity.Sex.ToString();
                userInfo.county = entity.Area;
                userInfo.updateTime = entity.LastUpdatedTime.TimeToString("yyyy-MM-dd HH:mm:ss");
                userInfo.token = "--";
                userInfo.realName = entity.Name;
                userInfo.province = entity.Province;
                userInfo.phone = entity.MobilePhone;
                userInfo.createTime = entity.CreatedTime.TimeToString("yyyy-MM-dd HH:mm:ss");
                if (entity.IsLocked)
                    userInfo.lockTime = entity.StateUpdateTime;
                else
                    userInfo.lockTime = null;

                userInfo.street = entity.Street;
                userInfo.idcard = entity.IDCard;
                userInfo.loginName = entity.CardNo;
                userInfo.unlockTime = null;
                userInfo.idcardType = 0;
                userInfo.iconUrl = "";
                userInfo.email = "";

                //DONE:晓阳 这里返回登录用户信息
                throw new NotImplementedException();

                return userInfo;
            }

        }


        /// <summary>
        /// 储值卡充值/储油卡充值/机器卡取现
        /// </summary>
        /// <param name="entityId"></param>
        /// <param name="money"></param>
        /// <returns></returns>
        public OperationResult Recharge(long entityId, double money)
        {
            using (var scope = DbScopeFactory.Create())
            {
                var customer = GetById(entityId);
                if (customer == null)
                    return new OperationResult(OperationResultType.QueryNull);

                var beforeMoney = customer.Balance;
                
                

                var nEntity = new MoneyChange();
                nEntity.Id = IdMaker.NewId();
                nEntity.GroupId = nEntity.Id;
                nEntity.MoneyType = 100;
                nEntity.Code = "";
                nEntity.UserId = customer.Id;
                
                //钱就是直接加多少元   油就是多少KG 所以要*1000 变为G存储
                if (customer.CardType == 2)
                {
                    
                    nEntity.Name = "客户[" + customer.CardNo + "]通过现金充值[" + money*1000 + "]g";
                    nEntity.MoneyBefore = customer.Balance;
                    nEntity.Money = money*1000;
                    nEntity.MoneyAfter = customer.Balance + nEntity.Money *1000;

                    customer.Balance += money * 1000;
                }
                else
                {
                    
                    nEntity.Name = "客户[" + customer.CardNo + "]通过现金充值[" + money + "]元";
                    nEntity.MoneyBefore = customer.Balance;
                    nEntity.Money = money;
                    nEntity.MoneyAfter = customer.Balance + nEntity.Money;

                    customer.Balance += money;
                }
                UpdateEntity(customer);

                MoneyChangeContract.AddEntity(nEntity);

                var result = scope.SaveChanges() > 0 ? OperationResult.Success : OperationResult.NoChanged;
                return result;
            }
        }

        /// <summary>
        /// 卡余额查询
        /// </summary>
        /// <param name="cardNo">卡号</param>
        /// <returns></returns>
        public CustomerApiInfo GetByCardNo(string cardNo)
        {
            using (DbScopeFactory.CreateReadOnly())
            {
                var p = SingleOrDefault(t => t.CardNo == cardNo);
                if (p == null)
                    return null;

                //1 储值 2 储油 3 售油机 管理卡4服务中心
                Dictionary<int, string> dic = new Dictionary<int, string>();
                dic.Add(1, "储值");
                dic.Add(2, "储油");
                dic.Add(3, "售油机");

                CustomerApiInfo info = new CustomerApiInfo { Id = p.Id + "", PhysicalNo = p.PhysicalNo, CardNo = p.CardNo, Denomination = p.Denomination, LimitProductName = p.LimitProduct?.Name, Name = p.Name, CardType = p.CardType, Balance = p.Balance, IsBurn = p.IsBurn };
                info.CardTypeName = dic[info.CardType];

                return info;
            }
        }

    }
}
